package api

import (
	imageMarge "changeme/imageMarge"
	"changeme/imageMarge/entity"
	"context"
	"log"
	"os"
	"os/exec"
	"time"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type MergeRes struct {
	ctx context.Context
}

func NewMergeRes() *MergeRes {
	return &MergeRes{}
}

func (a *MergeRes) SetContext(ctx context.Context) {
	a.ctx = ctx
}

func (a *MergeRes) CloseApp() {
	// 解绑所有事件
	runtime.EventsOffAll(a.ctx)
	// 退出系统
	os.Exit(0)
}

func (a *MergeRes) OpenFileDlg() (position []entity.Plist) {
	opts := runtime.OpenDialogOptions{}
	filePath, err := runtime.OpenMultipleFilesDialog(a.ctx, opts)
	if err != nil {
		log.Println(err.Error())
		return nil
	}

	plist := imageMarge.MargeResAny(filePath, "")

	for k := range plist {
		plist[k].Path = filePath[k]
	}
	return plist
}

func (a *MergeRes) GetPosition(files []string) []entity.Plist {

	plist := imageMarge.MargeResAny(files, "")
	return plist
}

func (a *MergeRes) ExportImg(plistInfo []entity.Plist) {
	opts := runtime.OpenDialogOptions{}
	dirPath, err := runtime.OpenDirectoryDialog(a.ctx, opts)
	if err != nil {
		log.Println(err.Error())
		return
	}
	files := make([]string, 0)
	for _, v := range plistInfo {
		files = append(files, v.Path)
	}

	randomFileName := time.Now().Format("20060102150405.png")
	_ = imageMarge.MargeResAny(files, dirPath+"\\"+randomFileName)
	openDir(dirPath)
}

func openDir(dirPath string) {
	cmd := exec.Command("cmd.exe", "/c", "start "+dirPath)
	err := cmd.Start() //如果用start则直接向后运行
	if err != nil {
		log.Fatal(err)
	}
}
